import Vue from 'vue'
import Component from 'vue-class-component'
import '../share/shareStyle.css'
import ProdcutCopyItemClass from './productCopyItem.js'
import SortViewClass from '@/components/sortView.js'
import FilterViewClass from '@/components/filterView.js'
import SearchHeadClass from '@/components/searchHeadView.js'
import FlowListClass from '@/components/flowList.js'
import BlankPageClass from '@/components/blankPage.js'
import VueScroller from '@/components/VueScroller.vue'

@Component
export default class ProductCopyClass extends Vue {
  isCanLoading = true
  wrapperHeight = 0
  list = []
  showSort = false
  showFiter = false
  products = []

  filterItems = []
  sortItems = []
  sortSelect = {}

  word = ''
  currentPage = 1
  selectProduct = {}
  isScrollBottom = false
  noData = false

  created() {
    this.updateData = false
    this.products = this.$store.getters.topicProductArr
    this.getFilterItems()
    this.getSortItems()

    let mySelf = this
    eventBus.$on('filterForCopyProduct', function(val) {
      mySelf.filterChangeStatus()
      mySelf.handleFilterSort()
    })
  }

  setDefaultData () {
    this.isCanLoading = true
    this.wrapperHeight = 0
    this.list = []
    this.showSort = false
    this.showFiter = false
    this.currentPage = 1
    this.filterItems = []
    this.sortItems = []
    this.sortSelect = {}
    this.isScrollBottom = false
    this.word = ''
    this.noData = false
  }

  activated() {
    this.wrapperHeight = document.documentElement.clientHeight - 104
    if (this.updateData) {
      this.updateData = false
      this.getFilterItems()
      this.getSortItems()
      this.reloadProducts()
    }
  }

  async getFilterItems () {
    try {
      const response = await this.$axios.post('/buyer/v1/products/filters', {})
      if (response.status === 0) {
        this.filterItems = response.data
      }
    } catch (e) {
      console.log(e)
    }
  }

  async getSortItems () {
    try {
      const response = await this.$axios.post('/buyer/v1/products/sorts')
      if (response.status === 0) {
        this.sortItems = response.data
        this.sortSelect = this.sortItems[0]
      }
    } catch (e) {
      console.log(e)
    }
  }

  getParameters() {
    let params = {}
    let selectValue = this.$store.state.productCopyStore.copyProductSelectValue
    for (let obj in selectValue) {
      params[obj] = selectValue[obj]
    }
    params['pageSize'] = 10
    params['pageIndex'] = this.currentPage
    params['sortType'] = this.sortSelect.sortType
    params['sortId'] = this.sortSelect.sortId
    params['word'] = this.word

    return params
  }

  findProducts(pageIndex = 1) {
    let params = this.getParameters()
    params['pageIndex'] = pageIndex
    return this.$axios.post('/buyer/v1/products', params)
      .then(response => {
        if (response.status === 0) {
          if (pageIndex === 1) {
            this.list = []
          }
          return response.data.buyerProducts
        }
      })
  }

  reloadProducts() {
    this.currentPage = 1
    this.$refs.vueScrollerTopic.$el.scrollTop = 0
    this.findProducts(this.currentPage).then(products => {
      console.log('dddddddddddddd', products)

      if (products) {
        this.list = [...this.list, ...products]
      }
      this.showNodata()
    }).catch((e) => {
      this.noData = true
    })
  }

  showNodata() {
    if (!this.list || this.list.length <= 0) {
      this.noData = true
    } else {
      this.noData = false
    }
  }

  infiniteHandler($state) {
    this.findProducts(this.currentPage++).then(products => {
      console.log('dddddddddddddd', products)
      $state.loaded()
      if (products) {
        this.list = [...this.list, ...products]
        if (products.length < 10) {
          $state.complete()
        }
      } else {
        $state.complete()
      }
      this.showNodata()
    }).catch(() => {
      $state.complete()
      this.noData = true
    })
  }

  handleFilterSort() {
    this.$refs.vueScrollerTopic.refreshHandler()
  }

  beforeUpdate() {
  }

  loadData() {
    if (!this.isScrollBottom && this.isCanLoading) {
      this.getData()
    }
  }

  handleSearch (value) {
    this.word = value
    this.handleFilterSort()
  }

  get caculateHeight() {
    return 'height:' + String(this.wrapperHeight) + 'px'
  }

  // 点击排序按钮
  handlerShowSortView() {
    this.showFiter = false
    this.sortChangeStatus()
  }

  // 点击排序事件
  handlerSort(index) {
    this.sortSelect = this.sortItems[index]
    this.handleFilterSort()
    // console.log(index)
    setTimeout(() => {
      this.sortChangeStatus()
    }, 300)
  }

  sortChangeStatus () {
    this.showSort = !this.showSort
    let s = this.$refs.sort
    let f = this.$refs.filter
    if (this.showSort) {
      s.style = 'color:red'
      f.style = 'color:#000'
    } else {
      s.style = 'color:#000'
    }
  }

  // 点击筛选按钮
  handlerShowFilterView() {
    this.showSort = false
    this.filterChangeStatus()
  }

  // 处理点击筛选条件
  handlerFilter (index) {
    const value = this.filterItems[index]

    this.$store.dispatch('changeCopyProductCurrentSuperId', value.key)
    if (value.name === '品牌' && value.children && value.children.length > 0) {
      this.$router.push({name: 'copyBrandList', params: {datas: value.children}})
    } else if (value.children && value.children.length > 0) {
      this.$router.push({name: 'filterTerm', params: {title: value.name, items: value.children, type: 'product'}})
    }
  }

  handlerClearFilter (items) {
    if (items.children && items.children.length) {
      for (var i = 0; i < items.children.length; i++) {
        let item = items.children[i]
        this.handlerClearFilter(item)
      }
    } else {
      items.checked = false
    }
  }

  // 清除
  handerFilterCancel () {
    this.$store.commit('setCopyProductSelectFilter', {})
    for (var i = 0; i < this.filterItems.length; i++) {
      let item = this.filterItems[i]
      this.handlerClearFilter(item)
    }
    this.handleClearCache()
    // this.filterChangeStatus()
    // this.currentPage = 0
    // this.getData()
  }

  // 清除store
  handleClearCache() {
    this.$store.dispatch('clearCopyProductSelect')
  }

  handerFilterSure () {
    this.filterChangeStatus()
    this.handleFilterSort()
  }

  filterChangeStatus () {
    this.showFiter = !this.showFiter
    let f = this.$refs.filter
    let s = this.$refs.sort
    if (this.showFiter) {
      f.style = 'color:red'
      s.style = 'color:#000'
    } else {
      f.style = 'color:#000'
    }
  }

  // 选中copy的商品
  handlerChooseCell (value, select) {
    if (select) {
      this.products.push(value)
    } else {
      for (let i = 0; i < this.products.length; i++) {
        if (this.products[i].productId === value.productId) {
          this.products.splice(i, 1)
        }
      }
    }
  }

  handlerSelect(value) {
    if (this.products) {
      for (let i = 0; i < this.products.length; i++) {
        if (this.products[i].productId === value.productId) {
          return true
        }
        return false
      }
    }
  }

  // 确定copy
  handlerSelectedProduct () {
    this.$store.commit('setTopicProductArr', this.products)
    this.$router.go(-1)
  }

  createItems(e) {
    if (!this.list || this.list.length <= 0) {
      return
    }

    const item = this.list.map((value, index) => {
      return <ProdcutCopyItemClass selectArr={this.products} value={value} onSelected={(value, select) => this.handlerChooseCell(value, select)}></ProdcutCopyItemClass>
    })
    console.log(item)
    return item
  }

  analyseData (type) {
    let leftData = []
    let rightData = []
    for (var i = 0; i < this.list.length; i++) {
      if (i % 2 === 0) {
        leftData.push(this.list[i])
      } else {
        rightData.push(this.list[i])
      }
    }
    if (type === 0) {
      return leftData
    }
    return rightData
  }

  handlePop() {
    this.handerFilterCancel()
    this.showFiter = true
    this.showSort = true
    this.filterChangeStatus()
    this.sortChangeStatus()
    this.updateData = true
    this.setDefaultData()
    this.$router.go(-1)
  }

   // 瀑布流
  createLeftItems () {
    // 瀑布流左边数据
    const item = this.analyseData(0).map((value, index) => {
      return <ProdcutCopyItemClass style='width:100%;padding:0' selectArr={this.products} slot='leftItemName' value={value} onSelected={(value, select) => this.handlerChooseCell(value, select)}></ProdcutCopyItemClass>
    })
    return item
  }

  // 瀑布流右边数据
  createrightItems () {
    const item = this.analyseData(1).map((value, index) => {
      return <ProdcutCopyItemClass style='width:100%;padding:0' selectArr={this.products} slot='rightItemName' value={value} onSelected={(value, select) => this.handlerChooseCell(value, select)}></ProdcutCopyItemClass>
    })
    return item
  }

  render () {
    return (
      <div class = 'content'>
        <SearchHeadClass
        leftIcon = 'backIcon'
        onClickLeft = {this.handlePop}
        onValueChange = {value => { this.handleSearch(value) }}
        placeholder='搜索商品'>

        </SearchHeadClass>
        <dl class = 'shareStyleClass'>
          <dd ref='sort' onClick={this.handlerShowSortView}>默认排序 <icon style='position:relative;top:2px;left:4px' name = 'paixu' scale = '1.3'/></dd>
          <dd ref='filter' onClick={this.handlerShowFilterView}>筛选<icon style='position:relative;top:2px;left:4px' name = 'shaixuan' scale = '1.5'/></dd>
        </dl>

        <BlankPageClass onRefresh={this.reloadProducts} v-show={this.noData}></BlankPageClass>

        <SortViewClass defaultSort={(this.sortItems && this.sortItems.length > 0) ? this.sortItems[0] : {}} lists={this.sortItems} v-show={this.showSort} onDismiss={this.sortChangeStatus} onClick={index => this.handlerSort(index)} ></SortViewClass>
        <FilterViewClass items={this.filterItems} v-show={this.showFiter} height={this.wrapperHeight} onSure={this.handerFilterSure} onDismiss={this.handerFilterCancel} onClick={this.handlerFilter}></FilterViewClass>

        <VueScroller v-show={!this.noData} ref='vueScrollerTopic' height={this.wrapperHeight} infinite={this.infiniteHandler} refresh={this.reloadProducts}>
          {this.createItems()}
        </VueScroller>
      </div>
    )
  }
}
